// src/stores/user.js
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    userInfo: null,
    accessToken: null,
    refreshToken: null,
  }),
  actions: {
    login(userInfo, accessToken, refreshToken) {
      this.isLoggedIn = true;
      this.userInfo = userInfo;
      this.accessToken = accessToken;
      this.refreshToken = refreshToken;
      // 将access_token和refresh_token保存到localStorage中
      localStorage.setItem('access_token', accessToken);
      localStorage.setItem('refresh_token', refreshToken);
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    logout() {
      this.isLoggedIn = false;
      this.userInfo = null;
      this.accessToken = null;
      this.refreshToken = null;
      // 清除localStorage中的access_token和refresh_token
      localStorage.removeItem('access_token');
      localStorage.removeItem('refresh_token');
      localStorage.removeItem('userInfo');
    },
    initializeFromLocalStorage() {
      const accessToken = localStorage.getItem('access_token');
      const refreshToken = localStorage.getItem('refresh_token');
      const userInfo = localStorage.getItem('userInfo');
      if (accessToken && refreshToken) {
        this.accessToken = accessToken;
        this.refreshToken = refreshToken;
        this.isLoggedIn = true;
      }
      if (userInfo) {
        this.userInfo = JSON.parse(userInfo);
      }
    },
  },
});
